const { formatTime } = require('../../utils/util')
const app = getApp();
const audioContext = app.globalData.isBgMusic ? wx.getBackgroundAudioManager() : wx.createInnerAudioContext();
Page({
  data: {
    nvabarData: {
      title: '',
      transmit: ''
    },
    clickStop: false,
    currentTab: 0,
    sliderOffset: 0,
    sliderWidth: 0,
    swiperHeight: 0,
    audioPlaying: false,
    currentAudioId: null,
    audioCurrentTime: 0, // 播放器实际时间
    audioDuration: 100,
    audioDisplayTime: 0,        // 显示的时间（与Slider同步）
    audioSliderValue: 0,        // Slider的显示值
    isAudioSeeking: false,      // 是否正在拖动
    audioSeekTarget: 0,         // 跳转目标时间
    audioSeekTimer: null,       // 跳转防抖定时器
    audioUpdateInterval: null,
    tabList: [
      {
        title: '音频列表',
        icon: '/images/audio-icon.png',
        num: 3,
      },
      {
        title: '视频列表',
        icon: '/images/video-icon.png',
        num: 4,
      },
      {
        title: '音乐列表',
        icon: '/images/music.png',
        num: 2,
      }
    ],
    audioList: [
      {
        id: 1,
        title: '第一课时',
        duration: '02:26',
        time: 146,
        src: 'https://cdn.foruhealth.cn/fwf/FWF_EP1-3B.mp3',
        file: 'https://cdn.foruhealth.cn/fwf/pic/FWF_EP5-2B.png',
        size: '3.2MB'
      },
      {
        id: 2,
        title: '第二课时',
        duration: '02:16',
        time: 136,
        src: 'https://cdn.foruhealth.cn/fwf/FWF_EP5-2B.mp3',
        file: 'https://cdn.foruhealth.cn/fwf/pic/FWF_EP5-1B.png',
        size: '3.1MB'
      },
      {
        id: 3,
        title: '第三课时',
        duration: '04:37',
        time: 277,
        src: 'https://cdn.foruhealth.cn/fwf/FWF-EP5-1B.mp3',
        file: 'https://cdn.foruhealth.cn/fwf/pic/FWF_EP5-2B.png',
        size: '5.6MB'
      },
    ],
    videoList: [
      {
        id: 1,
        title: '视频1',
        type: '单词',
        coverUrl: '/images/play-icon.png',
        duration: '06:05',
        updateTime: '2025-10-31',
        size: '10.2MB',
        videoSrc: 'https://cdn.foruhealth.cn/fwf/video/1.mp4',
        views: '12.5k',
      },
      {
        id: 2,
        title: '视频2',
        type: '句子',
        coverUrl: '/images/play-icon.png',
        duration: '06:10',
        updateTime: '2025-10-31',
        size: '10.6MB',
        videoSrc: 'https://cdn.foruhealth.cn/fwf/video/2.mp4',
        views: '8.3k',
      },
      {
        id: 3,
        title: '视频3',
        type: '语法',
        coverUrl: '/images/play-icon.png',
        duration: '06:15',
        updateTime: '2025-10-31',
        size: '10.8MB',
        videoSrc: 'https://cdn.foruhealth.cn/fwf/video/3.mp4',
        views: '1.5k',
      },
      {
        id: 4,
        title: '视频4',
        type: '作文',
        coverUrl: '/images/play-icon.png',
        duration: '06:05',
        updateTime: '2025-10-31',
        size: '10.2MB',
        videoSrc: 'https://cdn.foruhealth.cn/fwf/video/1.mp4',
        views: '18.5k',
      }
    ],
    musicList: [
      {
        id: 9,
        title: '音乐1',
        duration: '01:24',
        src: 'https://cdn.foruhealth.cn/fwf/music/123.mp3',
        size: '2.2MB'
      },
      {
        id: 10,
        title: '音乐2',
        duration: '00:50',
        src: 'https://cdn.foruhealth.cn/fwf/music/Fun-with-Flupe.mp3',
        size: '1.2MB'
      }
    ],
  },

  onLoad(options) {
    const { title } = options;
    this.setData({
      'nvabarData.title':title
    })
    wx.setStorageSync('noTabNum', '');
    this.calculateSliderPosition();
    this.calculateSwiperHeight();
    this.initAudio()
  },
  onShow() {
    if (wx.getStorageSync('noTabNum')) {
      this.setData({
        currentTab: wx.getStorageSync('noTabNum')
      })
    }
  },
  onReady() {
    // 组件加载完成后再次计算，确保尺寸准确
    this.calculateSliderPosition();
  },

  initAudio() {
    // 设置音频事件监听
    audioContext.onPlay(() => {
      console.log('音频开始播放');
      this.setData({
        audioPlaying: true
      });
      this.startAudioProgressUpdate();
    });

    audioContext.onPause(() => {
      console.log('音频暂停');
      this.setData({
        audioPlaying: false
      });
      this.stopAudioProgressUpdate();
    });
    audioContext.onStop(() => {
      console.log('音频停止');
      if (this.clickStop || !app.globalData.isBgMusic) {
        this.clickStop = false
        return
      }
      console.log('用户点击了控制窗口的X按钮，音频已停止');
      this.setData({
        audioPlaying: false,
        currentAudioId: null
      });
      this.stopAudioProgressUpdate();
      if (this.data.audioSeekTimer) {
        clearTimeout(this.data.audioSeekTimer);
      }
    });
    audioContext.onEnded(() => {
      console.log('音频播放结束');
      this.setData({
        audioPlaying: false,
        audioCurrentTime: 0,
        audioDisplayTime: formatTime(0),
        audioSliderValue: 0
      });
      this.stopAudioProgressUpdate();
      // 播放结束自动下一首
      this.playOther('next');
    });

    audioContext.onError((res) => {
      console.error('音频播放错误:', res.errMsg);
    });

    audioContext.onCanplay(() => {
      console.log('音频可以播放');
      // 获取音频时长
      setTimeout(() => {
        this.setData({
          audioDuration: Math.floor(audioContext.duration),
        });
      }, 500)
    });

    // 音频跳转完成事件
    audioContext.onSeeked(() => {
      console.log('音频跳转完成');
      // 跳转完成后，同步显示时间和实际时间
      this.setData({
        isAudioSeeking: false,
        audioCurrentTime: this.data.audioSeekTarget,
        audioDisplayTime: formatTime(this.data.audioSeekTarget)
      });
    });

    // 音频时间更新事件
    audioContext.onTimeUpdate(() => {
      if (!this.data.isAudioSeeking) {
        const currentTime = Math.floor(audioContext.currentTime);
        this.setData({
          audioCurrentTime: currentTime,
          audioDisplayTime: formatTime(currentTime),
          audioSliderValue: currentTime
        });
      }
    });
    // 使用背景音乐 窗口按钮上一曲下一曲功能
    if (app.globalData.isBgMusic) {
      audioContext.onNext(() => {
        console.log('onNext')
        this.playOther('next');
      });
      audioContext.onPrev(() => {
        console.log('onPrev')
        this.playOther();
      });
    }
  },

  playOther(flag) {
    const list = app.globalData.nowList
    let playIndex = 0;
    if (flag) {
      if (app.globalData.playIndex < list.length - 1) {
        playIndex = app.globalData.playIndex + 1;
      }
    } else {
      if (app.globalData.playIndex > 0) {
        playIndex = app.globalData.playIndex - 1;
      } else {
        playIndex = list.length - 1;
      }
    }

    app.globalData.playIndex = playIndex;
    const item = list[playIndex]
    this.setPlayAudio(item)
  },

  setPlayAudio(item) {
    // 停止当前音频
    if (audioContext) {
      this.clickStop = true
      audioContext.stop();
    }

    // 设置新的音频
    this.setData({
      currentAudioId: item.id,
      audioCurrentTime: 0,
      audioDisplayTime: formatTime(0),
      audioSliderValue: 0,
      audioPlaying: false
    });


    audioContext.title = item.title;
    audioContext.epname = '未知';
    audioContext.singer = '未知';
    audioContext.coverImgUrl = item.file
    // 加载并播放新音频
    audioContext.src = item.src;

    if (!app.globalData.isBgMusic) {
      audioContext.autoplay = true;
    }
    console.log('开始播放音频:', item.title);
  },
  // 播放音频
  playAudio(e) {
    const item = e.currentTarget.dataset.item;
    const playIndex = e.currentTarget.dataset.index;
    app.globalData.playIndex = playIndex;

    const type = e.currentTarget.dataset.type;
    if (type == 'audio') {
      app.globalData.nowList = this.data.audioList
    } else {
      app.globalData.nowList = this.data.musicList
    }
    // 如果点击的是当前正在播放的音频
    if (this.data.currentAudioId === item.id) {
      if (this.data.audioPlaying) {
        audioContext.pause();
      } else {
        audioContext.play();
      }
      return;
    }
    this.setPlayAudio(item)
  },

  // 音频进度更新
  startAudioProgressUpdate() {
    this.stopAudioProgressUpdate(); // 先停止之前的定时器
  },


  // 停止音频进度更新
  stopAudioProgressUpdate() {
    if (this.data.audioUpdateInterval) {
      clearInterval(this.data.audioUpdateInterval);
      this.data.audioUpdateInterval = null;
    }
  },
  // 音频滑块拖动中 - 实时更新显示
  onAudioSliderChanging(e) {
    const value = e.detail.value;
    this.setData({
      audioSliderValue: value,
      audioDisplayTime: formatTime(value),
      isAudioSeeking: true
    });
  },

  // 音频滑块变化
  onAudioSliderChange(e) {
    const value = e.detail.value;
    // 清除之前的跳转定时器
    if (this.data.audioSeekTimer) {
      clearTimeout(this.data.audioSeekTimer);
    }
    this.setData({
      audioSeekTarget: value,
    });

    // 使用防抖，延迟执行跳转
    this.data.audioSeekTimer = setTimeout(() => {
      if (audioContext) {
        audioContext.seek(value);
      }
    }, 50);
  },


  // 计算滑块位置
  calculateSliderPosition() {
    const that = this;
    wx.createSelectorQuery().select('.tab-item').boundingClientRect(function (rect) {
      if (rect) {
        const tabWidth = rect.width;
        that.setData({
          sliderWidth: tabWidth,
          sliderOffset: that.data.currentTab * tabWidth
        });
      }
    }).exec();
  },

  // 计算swiper高度
  calculateSwiperHeight() {
    const that = this;
    wx.getSystemInfo({
      success: function (res) {
        const windowHeight = res.windowHeight;
        // 估算tab栏和头部高度
        const tabBarHeight = 80; // 约80rpx
        const headerHeight = 140; // 约140rpx
        const margin = 40; // 上下margin
        const swiperHeight = windowHeight * 2 - (tabBarHeight + headerHeight + margin);

        that.setData({
          swiperHeight: swiperHeight
        });
      }
    });
  },

  // 切换Tab
  switchTab(e) {
    const index = e.currentTarget.dataset.index;
    if (this.data.currentTab == index) return;

    this.setData({
      currentTab: index
    });

    this.calculateSliderPosition();
  },

  // swiper滑动事件
  onSwiperChange(e) {
    const current = e.detail.current;
    this.setData({
      currentTab: current
    });

    this.calculateSliderPosition();
  },
  // 跳转视频
  goVideoDetail(e) {
    if (this.data.audioPlaying) {
      audioContext.pause();
    }
    wx.setStorageSync('noTabNum', this.data.currentTab);
    const item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: `/pages/video/video?item=${JSON.stringify(item)}`,
    })
  },
  // 预览
  preview(e) {
    const item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: `/pages/preview/preview?title=${item.title}&file=${item.file}`,
    })
  },

  // 录制
  record(e) {
    if (this.data.audioPlaying) {
      audioContext.pause();
    }
    const item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: `/pages/camera/camera?item=${JSON.stringify(item)}`,
    })
  },
});